import React, {FC, useEffect, useState} from 'react';
import {Pagination} from "antd";
import {useLocation, useNavigate, useSearchParams} from "react-router-dom";
import {LIST_PAGE_PARAM_KEY, LIST_PAGE_SIZE, LIST_PAGE_SIZE_PARAM_KEY} from "../constants";

type PropsType = {
    total: number
}
const ListPage: FC<PropsType> = (props: PropsType) => {
    const {total} = props
    const [current, setCurrent] = useState(1);
    const [pageSize, setPageSize] = useState(LIST_PAGE_SIZE);


    // 从url中获取page和pageSize，同步到分页组件
    const [searchParams] = useSearchParams()
    useEffect(() => {
        const page = parseInt(searchParams.get(LIST_PAGE_PARAM_KEY) || '') || 1
        const pageSize = parseInt(searchParams.get(LIST_PAGE_SIZE_PARAM_KEY) || '') || LIST_PAGE_SIZE
        setCurrent(page)
        setPageSize(pageSize)
    }, [searchParams]);

    // page pageSize改变时，跳转url
    const nav = useNavigate()
    const {pathname} = useLocation()
    const handlOnChange = (page: number, pageSize: number) => {
        console.log('handlOnChange', page, pageSize)
        searchParams.set(LIST_PAGE_PARAM_KEY, page.toString())
        searchParams.set(LIST_PAGE_SIZE_PARAM_KEY, pageSize.toString())
        nav({
            pathname,
            search: searchParams.toString()
        })
    };
    return (
        <Pagination current={current} pageSize={pageSize} total={total} onChange={handlOnChange}/>
    );
};

export default ListPage;
